﻿using System.Collections.Generic;
using Framework;

namespace Game
{
    public class ScenePetBehaviorComponent : IComponent
    {
        private ScenePetBTContext _context;
        private IBehaviorTree _behaviorTree;
        
        public ScenePetBehaviorComponent()
        {

        }
        
        public void Dispose()
        {
            if (_behaviorTree != null)
            {
                BTreeScheduler.Instance.StopTree(_behaviorTree);
            }
        }

        public void Setup(ScenePetEntity scenePet)
        {
            _context = new ScenePetBTContext();
            _context.sceneObject = scenePet;
            BTreeBuilder<SceneObjectBTContext> builder = new BTreeBuilder<SceneObjectBTContext>(_context);
            SceneObjectStateComposite stateComposite = new SceneObjectStateComposite();
            builder.BeginCustomComposite(stateComposite);
            builder.Actionable(new SceneObjectIdleActionable());
            builder.Actionable(new SceneObjectMoveActionable());
            builder.Actionable(new SceneObjectAttackActionable());
            builder.Actionable(new SceneObjectBeHitActionable());
            builder.Actionable(new SceneObjectDieActionable());
            builder.EndComposite();

            stateComposite.AddTransition(
                new SceneObjectDirectTransition(-1, ScenePetStates.Idle, 0));
            stateComposite.AddTransition(
                new ScenePetPressTransition(-1, ScenePetStates.Move, 1));
            stateComposite.AddTransition(
                new SceneObjectFaceAndHitTransition(-1, ScenePetStates.Attack, 2));
            stateComposite.AddTransition(
                new SceneObjectBeHitTransition(-1, ScenePetStates.BeHit, 3));
            stateComposite.AddTransition(
                new SceneObjectDieTransition(-1, ScenePetStates.Die, 4));
            _behaviorTree = builder.Build();
            BTreeScheduler.Instance.StartTree(_behaviorTree); 
        }

        public void PressLeft()
        {
            _context.sceneObject.SetFlipY(true);
            _context.isPressed = true;
        }
        
        public void PressRight()
        {
            _context.sceneObject.SetFlipY(false);
            _context.isPressed = true;
        }

        public void PressRelease()
        {
            _context.isPressed = false;
        }

        public void CollidedWith(SceneObjectEntity collidedEntity)
        {
            _context.collidedEntity = collidedEntity;
        }

        public void BeHit(SceneObjectEntity attackEntity)
        {
            _context.attackEntity = attackEntity;
        }

        public bool IsPressed()
        {
            return _context.isPressed;
        }
    }
}